 //
//  ViewController.m
//  唧歪
//
//  Created by MWJ on 15/7/6.
//  Copyright (c) 2015年 MWJ. All rights reserved.
//

#import "ViewController.h"
#import "AppDelegate.h"
#import "AnnotationView.h"
#import "Bubble.h"
#import <CoreLocation/CoreLocation.h> //凉席皮的
#import <MapKit/MapKit.h>
#import "RegisteredViewController.h"  //注册/登录界面
#import "PostingViewController.h" //发帖界面
#import "HotPostViewController.h"  //热帖界面
#import "PostDetailsViewController.h" //帖子详情界面
#import "modalViewController.h"
#import "ImageCompression.h"
#import "newsViewController.h"
#import <MapKit/MapKit.h>
#import "SVAnnotation.h"
#import "WGS84TOGCJ02.h"

#define roundIDURL @"https://app.jiwaipro.com:8888/index.php/JiWai/seek_homeId"
#define PostdetailsURL @"https://app.jiwaipro.com:8888/index.php/JiWai/postAccording"
#define personalDataURL @"https://app.jiwaipro.com:8888/index.php/JiWai/PersonalCenter" //个人资料URL
#define browseNumberURL @"https://app.jiwaipro.com:8888/index.php/JiWai/browse"  //浏览数

@interface ViewController ()<MKMapViewDelegate>{
    AppDelegate *app;
    CLLocationManager *locationManager;
    CLGeocoder *geocoder;
    CLPlacemark *Placemark;
    NSDictionary *roundArray1;
    NSMutableArray *roundArray;  //所有用户
    NSMutableArray *tourArray;
    NSMutableArray *idArray;
    NSMutableArray *perArray;
    NSMutableArray *postDetailArray;
    NSMutableArray *Personalarray;
    NSMutableArray *ImageArray;
    NSMutableArray *locaImageArray;
    int idindex;
    int judge;
    int intid;
    NSString *userId;
    UIButton *pinButton;
    int buttonInt;
    int imageInt;
    NSString *mess_tag;
    NSString *browseNumberStr;
    NSString *messageid;
    AnnotationView *oneView;
    NSMutableArray *newsArray;
    NSString *locaImage;
}
@end

@implementation ViewController


#pragma mark - 页面即将加载
- (void)viewWillAppear:(BOOL)animated
{
    [app isConnectionAvailable];
    if ([app.Existence isEqualToString:@"1"]) {
    }else{
        [super viewWillAppear:animated];
        app.defaults = [NSUserDefaults standardUserDefaults];
        app.user_id = [app.defaults objectForKey:@"yonghu"];
        self.mapview.delegate = self;
        //周边信息
        [self round];
        //开始定位
        [locationManager startUpdatingLocation];
        [self loading];
        app.Existence = @"0";
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.mapview.mapType = MKMapTypeStandard;
    self.mapview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.locationArray = [NSMutableArray array];
    newsArray = [NSMutableArray array];
    postDetailArray=[NSMutableArray array];
    tourArray = [NSMutableArray array];
    perArray = [NSMutableArray array];
    ImageArray=[NSMutableArray array];
    

    self.HeadportraitImage.layer.masksToBounds = YES;
    self.HeadportraitImage.layer.cornerRadius = self.HeadportraitImage.bounds.size.width/2;
    _xxlab.backgroundColor = [UIColor redColor];
    _xxlab.textColor = [UIColor whiteColor];
    _xxlab.layer.masksToBounds = YES;
    _xxlab.layer.cornerRadius = _xxlab.bounds.size.width/2;
    _xxlab.layer.borderColor = [UIColor redColor].CGColor;
    _xxlab.layer.borderWidth = 1.0;
    _xxlab.textAlignment = NSTextAlignmentCenter;
    _xxlab.hidden = YES;
    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    //创建右边菜单按钮
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"02.png"] style:UIBarButtonItemStylePlain target:self action:@selector(rightmenu)];
    self.navigationItem.rightBarButtonItem = item;
    
    //下拉菜单
    [self menu];
    //创建左边菜单
    UIBarButtonItem *leftitem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"个人中心.png"] style:UIBarButtonItemStylePlain target:self action:@selector(personmenu)];
    self.navigationItem.leftBarButtonItem = leftitem;
    self.navigationController.navigationBar.translucent = NO;
    
    if ([[UIDevice currentDevice].systemVersion doubleValue]>=8.0) {
        [locationManager requestAlwaysAuthorization];
    }
    //创建定位管理器
    locationManager = [[CLLocationManager alloc] init];
    geocoder=[[CLGeocoder alloc]init];
    //设置返回全部信息
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    //设置定位精度
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    locationManager.delegate=self;
    locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 8.0)
    {
        //设置定位权限 仅ios8有意义
        [locationManager requestWhenInUseAuthorization];// 前台定位
        
        //  [locationManager requestAlwaysAuthorization];// 前后台同时定位
    }
    imageInt = 0;
    NSTimer *timer=[[NSTimer alloc]init];
    timer=[NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(timetoRefresh) userInfo:nil repeats:YES];
    
}
-(void)loading{
    Personalarray = [NSMutableArray array];
    NSString *poststr =[NSString stringWithFormat:@"user_id=%@",app.user_id];
    [self londingPath:personalDataURL Str:poststr];
}
-(void)londingPath:(NSString *)path Str:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    Personalarray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    [self performSelectorOnMainThread:@selector(refreshData1:) withObject:Personalarray waitUntilDone:YES];
    }];
}
- (void)refreshData1:(NSArray *)sender{
    if (sender[0] == [NSNull null]) {
    }else{
    app.jf = [NSString stringWithFormat:@"%@",sender[0][0][@"user_count"]];
    }
    newsArray = sender[1];
    if (sender[1] == [NSNull null]) {
        self.message.hidden = YES;
        _xxlab.hidden = YES;
    }else{
        _xxlab.text = [NSString stringWithFormat:@"%lu",(unsigned long)newsArray.count];
        self.message.hidden = NO;
        _xxlab.hidden = NO;
    }
    app.appnewsArray = Personalarray[1];
    app.appPersonArray = Personalarray[0];
}

#pragma mark - 定时刷新，10分钟刷一次
-(void)timetoRefresh{
    [self round];
}

#pragma mark - 页面即将消失
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.mapview.delegate = nil;
    [app.LeftSlideVC setPanEnabled:NO];
    
}
- (BOOL)locationManagerShouldDisplayHeadingCalibration:(CLLocationManager *)manager{//遇到电磁干扰时，是否弹出按8字形摆动iPhone校准指南针的界面。
    return YES;
}
#pragma mark - 定位
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    if (error.code==kCLErrorLocationUnknown) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"无法获取到当前位置"delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }else if (error.code==kCLErrorNetwork){
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"网络异常"delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }else if (error.code==kCLErrorDenied){
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"您的iPhone禁用获取位置服务"delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}
//CLLocationManager委托方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //得到newLocation
    CLLocation *loc = [locations objectAtIndex:0];
    //判断是不是属于国内范围
    if (![WGS84TOGCJ02 isLocationOutOfChina:[loc coordinate]]) {
        //转换后的coord
        self.coordinate = [WGS84TOGCJ02 transformFromWGSToGCJ:[loc coordinate]];
    }
    [locationManager stopUpdatingLocation];
    _longitude = self.coordinate.longitude;
    _latitude = self.coordinate.latitude;
    if (loc!=nil) {
        //停止获取地址位置
        [locationManager stopUpdatingLocation];
        //转换地址
        [geocoder reverseGeocodeLocation:loc completionHandler:^(NSArray *placemarks, NSError *error) {
            if (error==nil&&[placemarks count]>0) {
                Placemark=[placemarks lastObject];
                NSString *s1=[[NSString alloc]init];
                //地标的名字
                s1=[NSString stringWithFormat:@"%@",Placemark.name];
            }else{
                UIAlertView *Alert = [[UIAlertView alloc]initWithTitle:@"错误提示" message:@"获取失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [Alert show];
                
            }
        }];
    }
    CLLocationCoordinate2D coordinate = {_latitude,_longitude};
    MKCoordinateRegion region = MKCoordinateRegionMake(coordinate, MKCoordinateSpanMake(0.05, 0.05));
    [self.mapview setRegion:region animated:NO];
    [self.mapview showsUserLocation];
}
-(void)refreshData{
    
}
-(void)londingPath1:(NSString *)path Str1:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        postDetailArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:postDetailArray waitUntilDone:YES];
    }];
}
-(void)refreshData:(NSMutableArray *)sender{
    app.appdetailArray = postDetailArray;
    for (NSDictionary *tx in postDetailArray[0]) {
        NSString *headportrait = [NSString stringWithFormat:@"%@",tx[@"user_headPortrait"]];
        NSURL *url=[NSURL URLWithString:headportrait];
        self.HeadportraitImage.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    }
    for(NSDictionary *dic in postDetailArray[1]){
        userId = [NSString stringWithFormat:@"%@",dic[@"user_id"]];
        self.labtime.text=[NSString stringWithFormat:@"%@",dic[@"message_time"]];  //帖子发布时间
        self.labcount=[NSString stringWithFormat:@"%@",dic[@"message_showtime"]];  //帖子显示时长
        self.titleContent.text=[NSString stringWithFormat:@"%@",dic[@"message_content"]];   //帖子内容
        self.commentshu.text = [NSString stringWithFormat:@"回帖数：%@",dic[@"message_comment"]]; //帖子评论数
        mess_tag = [NSString stringWithFormat:@"%@",dic[@"message_tag"]]; //帖子类型
        //经纬度转换成地址
        CLLocationCoordinate2D coordinate;
        coordinate. latitude =  [[ NSString stringWithFormat : @"%@" , dic[@"message_latitude"] ] floatValue ];
        coordinate. longitude = [[ NSString stringWithFormat : @"%@" , dic[@"message_longitude"] ] floatValue ];
        CLLocation *newLocation=[[ CLLocation alloc ] initWithLatitude :coordinate. latitude longitude : coordinate. longitude ];
        [geocoder reverseGeocodeLocation :newLocation completionHandler :^( NSArray * placemarks, NSError * error)
         {
        MKPlacemark *placemark = [placemarks objectAtIndex : 0 ];
        self.labplace.text = [ NSString stringWithFormat : @"%@",placemark.subLocality];
        self.street.text = [NSString stringWithFormat:@"%@",placemark.thoroughfare];
         }];
        if ([dic[@"message_tag"] isEqualToString:@"1"]) {
            
            self.titleContent.text=@"[图片帖子]";   //图片帖子
            for(NSDictionary *dic in postDetailArray[2]){
                NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",dic[@"image_path"]]];
                UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
                
                ImageCompression *ima = [[ImageCompression alloc]init];
                [ima OriginImage:image scaleToSize:CGSizeMake(30, 30)];
                // 1> 生成文本附件
                NSTextAttachment *textAttach = [[NSTextAttachment alloc] init];
                textAttach.image = ima.scaledImage;
                
                // 2> 使用文本附件创建属性文本
                NSAttributedString *strA = [NSAttributedString attributedStringWithAttachment:textAttach];
                
                self.titleContent.attributedText = strA;

            }
            
        }else if([dic[@"message_tag"] isEqualToString:@"2"]){
            self.titleContent.text=@"[语音帖子]";   //语音帖子
        }else{
            self.titleContent.text=[NSString stringWithFormat:@"%@",dic[@"message_content"]];   //帖子内容
        }
    }
    
        // 计时器
        NSTimer *countdownTimer=[[NSTimer alloc]init];
        countdownTimer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(TheCountDown) userInfo:nil repeats:YES];
    
}
-(void)TheCountDown{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];//设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];
    NSDateFormatter * dm = [[NSDateFormatter alloc]init];
    //指定输出的格式   这里格式必须是和上面定义字符串的格式相同，否则输出空
    [dm setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate * newdate = [dm dateFromString:self.labtime.text];
    
    
    int showtimeint = [self.labcount intValue];
    int dd = [newdate timeIntervalSince1970] + showtimeint*60 - (long)[datenow timeIntervalSince1970];
    if (dd<0) {
        self.detailsView.hidden = YES;
        self.blackView.hidden = YES;
        self.localButton.hidden = NO;
        CGAffineTransform pTransform = CGAffineTransformMakeTranslation(0, 0);
        //使视图使用这个变换
        self.detailsView.transform = pTransform;
        [UIView commitAnimations];
        [self.UpDown setImage:[UIImage imageNamed:@"up.png"] forState:UIControlStateNormal];
        buttonInt = 0;
        self.labcount = @"1000000";
        [self timetoRefresh];
        
    }else{
    int h = (dd / 60 / 60);
    int m = (dd - h * 60 * 60) / 60;
    int s = ((dd - h * 60 * 60 - m * 60));
    self.countdown.text=[NSString stringWithFormat:@"%d:%d:%d",h,m,s];
    dd --;
    }
}
-(void)rightmenu{
    if (self.sideMenu.isOpen)
        [self.sideMenu close];
    else
        [self.sideMenu open];
}

#pragma mark - 导航栏右边图标显示
-(void)menu{
    //第一个按钮
    UIView *postItem = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width/6.4, [UIScreen mainScreen].bounds.size.width/6.4)];
    [postItem setMenuActionWithBlock:^{
//        点击事件
        if (app.user_id == nil||[app.user_id isEqualToString:@""]) {
            UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            RegisteredViewController *reg = [sb instantiateViewControllerWithIdentifier:@"RegisteredVC"];
            [self.navigationController pushViewController:reg animated:YES];
        }else{
            UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            PostingViewController *post=[sb instantiateViewControllerWithIdentifier:@"postVC"];
            [self.navigationController pushViewController:post animated:YES];
        }
    }];
    UIImageView *postIcon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width/8, [UIScreen mainScreen].bounds.size.width/8)];
    [postIcon setImage:[UIImage imageNamed:@"发帖"]];
    UILabel *post = [[UILabel alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.width/8, [UIScreen mainScreen].bounds.size.width/8, 15)];
    post.text = @"发帖";
    post.textAlignment=NSTextAlignmentCenter;
    post.font = [UIFont boldSystemFontOfSize:14.0f];
    [postItem addSubview:postIcon];
    [postItem addSubview:post];
    //第二个按钮
    UIView *hotpostItem = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width/6.4, [UIScreen mainScreen].bounds.size.width/6.4)];
    [hotpostItem setMenuActionWithBlock:^{
        //点击事件
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        HotPostViewController *hotPost=[sb instantiateViewControllerWithIdentifier:@"hotPostVC"];
        [self.navigationController pushViewController:hotPost animated:YES];
        
    }];
    UIImageView *hotpostIcon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width/8, [UIScreen mainScreen].bounds.size.width/8)];
    [hotpostIcon setImage:[UIImage imageNamed:@"Action_Chat1@2x"]];
    UILabel *hotpost = [[UILabel alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.width/8, [UIScreen mainScreen].bounds.size.width/8, 15)];
    hotpost.text = @"热帖";
    hotpost.textAlignment=NSTextAlignmentCenter;
    hotpost.font = [UIFont boldSystemFontOfSize:14.0f];
    [hotpostItem addSubview:hotpostIcon];
    [hotpostItem addSubview:hotpost];
    self.sideMenu = [[HMSideMenu alloc] initWithItems:@[postItem, hotpostItem]];
    //按钮上下的间距
    [self.sideMenu setItemSpacing:10.0f];
    [self.view addSubview:self.sideMenu];
}

#pragma mark - 导航栏左边个人中心
-(void)personmenu{
    if (app.LeftSlideVC.closed)
    {
        [app.LeftSlideVC openLeftView];
    }
    else
    {
        [app.LeftSlideVC closeLeftView];
    }
}
-(void)ButtonClick:(UIButton *)sender{
    app.appmessageid=[NSString stringWithFormat:@"%ld",(long)sender.tag];
    app.appmeid=[NSString stringWithFormat:@"%ld",(long)sender.tag];
    self.detailsView.hidden = NO;
    CGFloat R  = (CGFloat) 255/255.0;
    CGFloat G = (CGFloat) 255/255.0;
    CGFloat B = (CGFloat) 255/255.0;
    CGFloat alpha = (CGFloat) 0.0;
    UIColor *myColorRGB = [ UIColor colorWithRed: R  green: G  blue: B  alpha: alpha  ];
    self.detailsView.backgroundColor = myColorRGB;
    self.blackView.hidden = NO;
    self.localButton.hidden = YES;
    NSString *poststr =[NSString stringWithFormat:@"message_id=%@",app.appmessageid];
    [self londingPath1:PostdetailsURL Str1:poststr];
    
    [self BrowseNumberPath:browseNumberURL Str:poststr];
}

-(void)BrowseNumberPath:(NSString *)path Str:(NSString *)str{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        browseNumberStr =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshDataBrowse:) withObject:browseNumberStr waitUntilDone:YES];
    }];
}
-(void)refreshDataBrowse:(NSString *)str{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - 显示所有用户
-(void)round{
    [self.mapview removeAnnotations:self.mapview.annotations];
    judge = 1;
    NSURL *url=[NSURL URLWithString:roundIDURL];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *poststr =[NSString stringWithFormat:@"message=%d",judge];
    NSData *data=[poststr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    roundArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    [self performSelectorOnMainThread:@selector(refreshData) withObject:roundArray waitUntilDone:YES];
        ImageArray = roundArray[roundArray.count - 1];
        for (int i=0;i<roundArray.count - 1;i++) {
        Bubble *bubble = [[Bubble alloc]init];
        bubble.message_id = roundArray[i][@"message_id"];
        [tourArray addObject:bubble.message_id];
        }
    [self all];
    }];
}

-(void)all{
    idArray = [NSMutableArray array];
    self.locationsMutArray=[NSMutableArray array];
    locaImageArray = [NSMutableArray array];
    idArray = [NSMutableArray array];
    for (int i=0;i<roundArray.count - 1;i++) {
        AnnotationView *tourLocation=[[AnnotationView alloc]init];
        //把经度纬度封装
        tourLocation.title = ImageArray[i][0][@"user_headPortrait"];
        tourLocation.messageId = roundArray[i][@"message_id"];
        tourLocation.tagInt = [NSString stringWithFormat:@"%d",i];
        tourLocation.coordinate=CLLocationCoordinate2DMake([roundArray[i][@"message_latitude"] doubleValue],[roundArray[i][@"message_longitude"] doubleValue]);
        locaImage = tourLocation.title;
        [locaImageArray addObject:tourLocation.title];
        [idArray addObject:tourLocation.messageId];
        [self.locationsMutArray addObject:tourLocation];
    }
    [self loadannotation];
//    [self currentPosition:self.localButton];
}
-(void)loadannotation{
    [self addannotation];
    [locationManager startUpdatingLocation];
    imageInt = -1;
}
-(void)addannotation{
    [self.mapview removeAnnotations:self.mapview.annotations];
    [self.mapview addAnnotations:self.locationsMutArray];
}
#pragma mark - 自定义大头针
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    ++imageInt;
    if ([annotation isKindOfClass:[AnnotationView class]]) {
        static NSString *Indetifier = @"customReuseIndetifier";
        AnnotationView *annotationView = [[AnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:Indetifier];
        if (imageInt >= (int)locaImageArray.count) {
        }else{
            annotationView = [self.mapview.annotations objectAtIndex:imageInt];
            annotationView.image = [UIImage imageNamed:@"MapAnnotation.png"];
            annotationView.frame=CGRectMake(0, 0, 45, 51);
            annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
            NSURL *url=[NSURL URLWithString:annotationView.title];
            pinButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 45, 45)];
            [pinButton addTarget:self action:@selector(ButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            [pinButton setBackgroundImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:url]] forState:UIControlStateNormal];
            pinButton.layer.masksToBounds = YES;
            pinButton.layer.cornerRadius = pinButton.bounds.size.width/2;
            annotationView.selected=YES;
            [annotationView addSubview:pinButton];
            pinButton.tag = [annotationView.messageId intValue];
        }
        return annotationView;
    }
    return nil;
}
- (IBAction)down:(id)sender {
    self.detailsView.hidden = YES;
    self.blackView.hidden = YES;
    self.localButton.hidden = NO;
    CGAffineTransform pTransform = CGAffineTransformMakeTranslation(0, 0);
    //使视图使用这个变换
    self.detailsView.transform = pTransform;
    [UIView commitAnimations];
    [self.UpDown setImage:[UIImage imageNamed:@"up.png"] forState:UIControlStateNormal];
    buttonInt = 0;
}
- (IBAction)detailsButton:(id)sender {
    app.quickOrNot = @"0";
    PostDetailsViewController *postDetail=[self.storyboard instantiateViewControllerWithIdentifier:@"detailVC"];
    [self.navigationController pushViewController:postDetail animated:YES];
}

- (IBAction)UpButton:(id)sender {
    modalViewController *moda=[self.storyboard instantiateViewControllerWithIdentifier:@"modalVC"];
    [self.navigationController presentViewController:moda animated:YES completion:nil];
}
- (IBAction)currentPosition:(id)sender {
    //开始定位
//    [self.mapview removeAnnotations:self.mapview.annotations];
    [self addannotation];
//    [self timetoRefresh];
    [locationManager startUpdatingLocation];
    imageInt = -1;
}

- (IBAction)xx:(id)sender {
    newsViewController *news=[self.storyboard instantiateViewControllerWithIdentifier:@"newsVC"];
    [self.navigationController pushViewController:news animated:YES];
}
@end
